package com.wjx.article_sys.service.impl;

import com.wjx.article_sys.dao.AdminMapper;
import com.wjx.article_sys.entity.Admin;
import com.wjx.article_sys.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpSession session;


    @Override
    public void login(String userName,String password,int isLoginBack,
                      int isArticleDetailLogin,Integer aId) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        Admin admin = adminMapper.queryByUsernameAndPassword(userName, password);
        if (admin == null) {
            //登录失败
            response.getWriter().write("<script>alert('用户名或密码错误');" +
                    "window.location.href='/tologin?isLoginBack=" + isLoginBack +
                    "&isArticleDetailLogin=" + isArticleDetailLogin +"&aId="+aId+"'"+ "</script>");
        } else {
            //登录成功
            session.setAttribute("userName", userName);
            session.setAttribute("photo",admin.getPhoto());
            if (isArticleDetailLogin == 1) {
                response.getWriter().write("<script>alert('登录成功');" +
                        "window.location.href='/front/article?id="+aId+"'"+"</script>");
            }
            else if (isLoginBack == 1){
                response.getWriter().write("<script>alert('登录成功');" +
                        "window.location.href='/back/index'</script>");
            }else {
                response.getWriter().write("<script>alert('登录成功');" +
                        "window.location.href='/'</script>");
            }

        }
    }

    @Override
    public void register(Admin admin) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            adminMapper.insertAdmin(admin);
            response.getWriter().write("<script>alert('注册成功,前往登录');" +
                    "window.location.href='/tologin'" + "</script>");
        }catch (Exception e){
            response.getWriter().write("<script>alert('注册失败,请重新注册');"  +
                    "window.location.href='/toRegister'" + "</script>");
        }
    }

    public Admin queryByUsername(String username){
        return adminMapper.queryByUsername(username);
    }

}
